﻿/*
 * @Description:http服务文件
 * @Author: maskMan
 * @LastEditTime: 2025-03-17 09:28:20
 */
const fs = require('fs')
const https = require('https')
const express = require('express')
const jwt = require('jsonwebtoken')
var app: any = express()
import { conf } from './config'
const parser = require('body-parser')
import { expressjwt } from 'express-jwt'
import HttpRequest from './request'
import path from 'path'
import { NDefine } from '../types/define'
export const AppListen = function () {
  app.all('*', function (req, res, next) {
    try {
      res.header('Access-Control-Allow-Origin', '*')
      res.header('Access-Control-Allow-Methods', '*')
      res.header('Access-Control-Allow-Headers', '*')
      if (req?.originalUrl?.startsWith('/web')) {
        res.header('Content-Type', 'text/html')
      } else {
        res.header('Content-Type', 'application/json')
      }
      next()
    } catch (error) {
      console.log(error)
    }
  })
}
//获取APP实力
export const getApp = function (): any {
  if (!app) {
    app = express()
  }
  return app
}
/**设置中间件 */
export const AppMiddleWare = function (): boolean {
  try {
    const exclude = []
    const regKeyList = ['/', `login`]
    for (let i = 0; i < regKeyList.length; i++) {
      exclude.push(new RegExp('^/' + regKeyList[i]))
    }
    app.use(parser.urlencoded({ extended: true })) //解析body
    app.use(express.json()) //解析JSON
    app.use(express.urlencoded({ extended: true })) //解析网址字符串
    const ejwt = expressjwt({ secret: conf.secretKey, algorithms: ['HS256'] }).unless({
      path: exclude
    })
    app.use(ejwt) //解析jwt
    app.use((err, req, res, next) => {
      if (err?.name == 'UnauthorizedError') {
        console.error(`用户无权限${req.originalUrl}`)
        return resSend(res, false, null, '无权限访问')
      } else {
        console.error('中间件报错', err)
        return resSend(res, false, null, '服务器错误')
      }
    }) //加载错误中间件
    return true
  } catch (error) {
    console.error('错误')
    return false
  }
  //session
  // app.use(session({ secret: conf.secret, resave: false, saveUninitialized: true })).unless({ path: [/^\/api\//] }); //session中间件
}
/**token签名
 * @param  data  签名数据
 * @param  string  返回格式
 */
export function jwtSign(data: NDefine.ISign): string {
  return jwt.sign(data, conf.secretKey, { expiresIn: conf.tokenExpires })
}
/**http 端口监听
 * @param  port  端口号
 */
export const httpListen = function (): Promise<boolean> {
  return new Promise((resolve) => {
    try {
      app.listen(conf.httpPort, function () {
        console.log(`http端口启动成功 ${conf.httpPort}`)
        resolve(true)
      })
    } catch (error) {
      console.error(error)
      resolve(false)
    }
  })
}
/**https 端口监听
 * @param  port  端口号
 */
export const httpsListen = function (): Promise<boolean> {
  return new Promise((resolve) => {
    try {
      const key = fs.readFileSync(`${__dirname}/../res/file/lz.lzmgame.com.key`)
      const cert = fs.readFileSync(`${__dirname}/../res/file/lz.lzmgame.com.crt`)
      https.createServer({ key: key, cert: cert }, app).listen(conf.httpPort, function () {
        console.log(`https端口启动成功 ${conf.httpPort}`)
        resolve(true)
      })
    } catch (error) {
      console.log(error)
      resolve(false)
    }
  })
}
/**监听静态目录
 */
export const createStaticWeb = function (): void {
  app.use('/web', express.static(path.join(__dirname, '../www/web')))
}
/**
 * @description: 服务返回
 * @param {*} res 服务
 * @param {boolean} status  结果
 * @param {Obj} data 数据
 * @param {string} msg 提示
 * @param {string} token  token
 * @return {*}
 */
export const resSend = function <T = any>(res, data: T = null, status: boolean, msg: string = '成功', token?: string): void {
  try {
    var retData: NDefine.IRes<T> = {
      status: status,
      msg: msg,
      data: data
    }
    if (token) {
      retData.token = token
    }
    res.send(JSON.stringify(retData))
  } catch (error) {
    console.error('resSend', retData)
  }
}
/**测试get接口 */
export const httpTestGet = async function (url: any, data?: any): Promise<any> {
  return await HttpRequest.get(url, data, 'http://127.0.0.1:13010')
}
/**测试Post接口 */
export const httpTestPost = async function (url: any, data: any): Promise<any> {
  return await HttpRequest.post(url, data, 'http://127.0.0.1:13010')
}
